package com.usian.admin.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.usian.admin.feign.ArticleFeign;
import com.usian.admin.feign.WemediaFeign;
import com.usian.admin.mapper.AdChannelMapper;
import com.usian.admin.mapper.AdSensitiveMapper;
import com.usian.admin.service.WemediaNewsAutoScanService;
import com.usian.common.aliyun.GreenImageForUrl;
import com.usian.common.aliyun.GreenTextFroContent;
import com.usian.common.exception.CatchCustomException;
import com.usian.model.admin.pojos.AdChannel;
import com.usian.model.article.pojos.ApArticle;
import com.usian.model.article.pojos.ApArticleConfig;
import com.usian.model.article.pojos.ApArticleContent;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.common.SensitiveWordUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.*;

@Service
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {

    @Autowired
    private WemediaFeign wemediaFeign;

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private AdChannelMapper adChannelMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void autoScanByMediaNewsId(Integer id) {
        // 检查参数
        if (id == null) {
            CatchCustomException.catchs(20001, "参数不能为空");
        }
        // 根据id 调用远程接口  获取文章信息
        WmNews wmNews = wemediaFeign.findById(id);
        if(wmNews == null){
            CatchCustomException.catchs(20001, "需要审核的文章没有找到，请检查ID");
        }
        // 文章状态 == 4 人工审核通过了  直接保存到数据库和创建索引
        if(wmNews.getStatus() == 4){
            this.saveAppArticle(wmNews);
            return;
        }
        // 文章状态  == 8  发布时间  <= 当前时间
        if(wmNews.getPublishTime() != null){
            if(wmNews.getStatus() == 8 && wmNews.getPublishTime().getTime() <= System.currentTimeMillis()){
                this.saveAppArticle(wmNews);
                return;
            }
        }
        // 文章状态  == 1  先判断 本公司维护的  敏感词   判断阿里云文本反垃圾检查    判断图片机器审核
        if(wmNews.getStatus() == 1){
            // 进行审核
            // 获取图文内容
            Map<String, Object> handleMap = this.handleTextAndImages(wmNews);
            // 敏感词查询
            boolean sensitiveBoolean =  this.handleSensitive((List<String>)handleMap.get("contents"),wmNews);
            if(!sensitiveBoolean){
                return;
            }
            boolean textBoolean = this.handleTextScan((List<String>)handleMap.get("contents"),wmNews);
            if(!textBoolean){
                return;
            }
          /*  boolean imagesBoolean = this.handleImagesScan((List<String>)handleMap.get("images"),wmNews);
            if(!imagesBoolean){
               return;
            }*/
            //            判断发布时间是否为空  如果不为空的话就定时发布
            if(wmNews.getPublishTime()!=null){
//                定时发布
                if (wmNews.getPublishTime().getTime()>System.currentTimeMillis()){
                    this.updateWmNews(wmNews,(short)8,"审核通过，待发布");
//                    发送  私信队列
                    long hs = wmNews.getPublishTime().getTime() - System.currentTimeMillis();
//                    消息
                    Message message= MessageBuilder
                            .withPayload(wmNews.getId().toString().getBytes(StandardCharsets.UTF_8))
                            .setHeader("x-delay",hs)
                            .build();
//                    发送消息
                    rabbitTemplate.convertAndSend("cjexchange","cj",message);
                    return;
                }
            }
            // 不定时 发布  确定 状态改成   9
            this.saveAppArticle(wmNews);
        }

    }

    @Autowired
    private GreenTextFroContent greenTextFroContent;

    @Autowired
    private GreenImageForUrl greenImageForUrl;

    @Autowired
    private AdSensitiveMapper adSensitiveMapper;


    // 敏感词查询
    private boolean handleSensitive(List<String> contents,WmNews wmNews){
        boolean flag = true;
        //初始化
        List<String> sensitives =  adSensitiveMapper.findAllSensitive();
        SensitiveWordUtil.initMap(sensitives);
        StringBuilder sb = new StringBuilder();
        for (String str:contents){
            sb.append(str);
        }
        Map<String,Integer> map  =  SensitiveWordUtil.matchWords(sb.toString());
        if(map.size()>0){
            this.updateWmNews(wmNews,(short)2,"文章中包含了敏感词！！！");
            flag = false;
        }
        return flag;
    }


    // 图片检查
    private boolean handleImagesScan(List<String> images,WmNews wmNews){
        boolean flag = true;
        try {
            Map map =  greenImageForUrl.imagesScan(images);
            if(!map.get("suggestion").equals("pass")){
                // 审核不通过！  == 2
                if(map.get("suggestion").equals("block")){
                    this.updateWmNews(wmNews,(short)2,"文章中有图片违规！");
                    flag = false;
                }
                // 疑似  == 3
                if(map.get("suggestion").equals("review")){
                    updateWmNews(wmNews,(short)3,"文章中有不确定图片，需要人工审核！");
                    flag = false;
                }
            }
        }catch (Exception e){
            flag = false;
        }
        return flag;
    }


    //审核文本内容
    private boolean handleTextScan(List<String> contents,WmNews wmNews){
        boolean flag = true;
        try {
           Map map =  greenTextFroContent.TextScan(contents);
           if(!map.get("suggestion").equals("pass")){
               // 审核不通过！  == 2
               if(map.get("suggestion").equals("block")){
                   this.updateWmNews(wmNews,(short)2,"文章内容中有敏感词！不能通过审核");
                   flag = false;
               }
               // 疑似  == 3
               if(map.get("suggestion").equals("review")){
                   updateWmNews(wmNews,(short)3,"文章内容中有不确定词汇，需要人工审核！");
                   flag = false;
               }
           }
        }catch (Exception e){
            flag = false;
        }
        return flag;
    }

    // 获取文本和图片内容
    /**
     * 提取文本内容和图片
     *
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        //文章的图文内容
        String content = wmNews.getContent();
        //存储纯文本内容
        List<String> contents = new ArrayList<>();
        //存储图片
        List<String> images = new ArrayList<>();

        List<Map> contentList = JSONArray.parseArray(content, Map.class);
        for (Map map : contentList) {
            if (map.get("type").equals("text")) {
                contents.add((String) map.get("value"));
            }

            if (map.get("type").equals("image")) {
                images.add((String) map.get("value"));
            }
        }

        // 获取封面图片  当前images ！=null  并且  布局  不能是0图
        if (wmNews.getImages() != null && wmNews.getType() != 0) {
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("contents", contents);
        resultMap.put("images", images);
        return resultMap;

    }

    /**
     *
     * @param wmNews 修改的文章内容
     * @param status 要修改的状态码
     * @param reason 失败的拒绝原因
     */
    private void updateWmNews(WmNews wmNews,Short status,String reason){
        // 修改状态   9
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wemediaFeign.updateById(wmNews);
    }

    /**
     * 发布--》
     * 保存三张表数据  1. article  2. config  3. content
     * @param wmNews
     */
    private void saveAppArticle(WmNews wmNews){
        // 保存自己
        ApArticle article =  this.saveArticle(wmNews);
        this.saveArticleConfig(article);
        this.saveArticleContent(article,wmNews);
        this.updateWmNews(wmNews,(short)9,"审核成功，发布！");
    }

    /**
     * 保存文章
     * @param wmNews
     * @return
     */
    private ApArticle  saveArticle(WmNews wmNews){
        ApArticle apArticle  = new ApArticle();
        apArticle.setChannelId(wmNews.getChannelId()); // 频道Id
        apArticle.setTitle(wmNews.getTitle()); // 文章标题
        apArticle.setLayout(wmNews.getType()); // 0图 1图 3图
        apArticle.setImages(wmNews.getImages()); //封面
        apArticle.setLabels(wmNews.getLabels()); // 标签
        apArticle.setCreatedTime(new Date()); // 创建时间
        apArticle.setLikes(0); // 喜欢
        apArticle.setCollection(0);  // 收藏
        apArticle.setComment(0); //评论
        apArticle.setViews(0); // 阅读数

        // 获取频道Id
        Integer channelId = apArticle.getChannelId();
        AdChannel adChannel = adChannelMapper.selectById(channelId);
        if(adChannel == null){
            apArticle.setChannelName("");
        }else{
            apArticle.setChannelName(adChannel.getName());
        }
        // 获取作者名称
        Integer wmUserId = wmNews.getUserId();
        WmUser wmUser =  wemediaFeign.findWmUserById(wmUserId);
        if(wmUser !=null){
            ApAuthor apAuthor =  articleFeign.findByName(wmUser.getName());
            if(apAuthor != null){
                apArticle.setAuthorName(apAuthor.getName());
                apArticle.setAuthorId(apAuthor.getId().longValue());
            }
        }

        return articleFeign.saveArticle(apArticle);
    }


    /**
     * 保存文章配置信息
     * @param apArticle
     */
    private void saveArticleConfig(ApArticle apArticle){
        ApArticleConfig apArticleConfig  = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsForward(true); // 默认可以转发
        apArticleConfig.setIsDelete(false); // 默认不删除
        apArticleConfig.setIsComment(true); // 默认可以评论
        apArticleConfig.setIsDown(false); // 默认下架

        articleFeign.saveArticleConfig(apArticleConfig);
    }

    /**
     * 保存文章图文内容
     * @param apArticle
     * @param wmNews
     */
    private void saveArticleContent(ApArticle apArticle,WmNews wmNews){
        ApArticleContent articleContent = new ApArticleContent();
        articleContent.setContent(wmNews.getContent());
        articleContent.setArticleId(apArticle.getId());
        articleFeign.saveArticleContent(articleContent);
    }




}
